package com.hjy.auth.web;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.hjy.auth.feign.MemberFeignService;
import com.hjy.auth.vo.MemberEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuth2Controller {
    @Autowired
    private MemberFeignService memberFeignService;

    @RequestMapping("/oauth/weibo/success")
    public String oauthWeibo(String code, HttpSession session) {
        // 获取 token
        Map<String,Object> map = new HashMap<>();
        map.put("client_id","238179560");
        map.put("client_secret","c1621c5333974b05476813ae806ec5a2");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth/weibo/success");
        map.put("code",code);;
        HttpResponse response = HttpRequest.post("https://api.weibo.com/oauth2/access_token")
                .form(map).execute();
        if (response.getStatus() != 200) {
            return "redirect:http://auth.gulimall.com/login";
        }
        String body = response.body();
        HashMap<String, String> stringStringHashMap = JSONUtil.toBean(body, new TypeReference<HashMap<String, String>>() {
        }, true);

        // 交给 Member 服务注册或登录
        MemberEntity memberEntity = memberFeignService.oauthLogin(stringStringHashMap);
        if (memberEntity != null) {
            session.setAttribute("loginUser",memberEntity);
            return "redirect:http://gulimall.com";
        }

        return "redirect:http://auth.gulimall.com/login";
    }
}
